package com.ruoyi.framework.shiro.util;

import com.ruoyi.framework.shiro.util.secret.Algorithm;
import com.ruoyi.framework.shiro.util.secret.MD5Util;
import com.ruoyi.framework.shiro.util.secret.SecurityUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.buf.HexUtils;

import java.nio.charset.StandardCharsets;

/**
 * 请求body和返回data加密工具
 */
public class EncryptUtils {

    private static final String NATIONAL = "NATIONAL";

    private EncryptUtils() {
    }


    public static String encrypt(String content, String secret, String encryptConfig) {
        if (StringUtils.equals(encryptConfig, NATIONAL)) {
            byte[] bytes = Algorithm.encryptSMS4PCS5Padding(content.getBytes(StandardCharsets.UTF_8), secret.getBytes(StandardCharsets.UTF_8));
            return HexUtils.toHexString(bytes);
        }

        secret = MD5Util.getMD5String(secret);
        return SecurityUtil.encryptAES(content, secret);
    }


    public static String decrypt(String content, String secret, String encryptConfig) {
        if (StringUtils.equals(encryptConfig, NATIONAL)) {
            byte[] dataBytes = HexUtils.fromHexString(content);
            byte[] bytes = Algorithm.decryptSMS4PCS5Padding(dataBytes, secret.getBytes(StandardCharsets.UTF_8));
            return new String(bytes, StandardCharsets.UTF_8);
        }

        String md5String = MD5Util.getMD5String(secret);
        return SecurityUtil.decryptAES(content, md5String);
    }
}
